package course.cmsc436.medicationmanager;

import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;

import android.content.Context;
import android.util.Log;

import course.cmsc436.medication.Medication;

public class MedicationSerializer {
	//http://stackoverflow.com/questions/4118751/how-do-i-serialize-an-object-and-save-it-to-a-file-in-android
	private static final String TAG = MedicationSerializer.class.getSimpleName();
	@SuppressWarnings("unchecked")
	public static ArrayList<Medication> getMedications(Context context) {
		try {
			FileInputStream fir = context.openFileInput("medications.dat");
			ObjectInputStream ois = new ObjectInputStream(fir);
			ArrayList<Medication> m = (ArrayList<Medication>)ois.readObject();
			ois.close();
			Log.d(TAG, "Finished read medications list from file. New list has a size of " + m.size());
			for(Medication ms : m ){
				Log.d(TAG, " "+ ms.getProprietaryName());
			}
			return m;
			
		} catch(Exception e) {
			Log.e(TAG, "Error reading medications:", e);
			return new ArrayList<Medication>();
		}
	}
	
	public static void saveMedications(ArrayList<Medication> meds,Context context) {
		try {
			FileOutputStream fos = context.openFileOutput("medications.dat", Context.MODE_PRIVATE);
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(meds);
			oos.close();
			Log.d(TAG, "Finished writing medications list to file.");
		} catch(Exception e) {
			Log.e(TAG, "Error saving medications:", e);
		}
	}
}
